package com.kingint.web.admin.serve.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kingint.common.unitedresult.K;
import com.kingint.mbg.group.Insert;
import com.kingint.mbg.group.Update;
import com.kingint.mbg.sys.entity.Notice;
import com.kingint.mbg.sys.entity.NoticeUser;
import com.kingint.mbg.sys.entity.UmsMember;
import com.kingint.web.sys.service.NoticeService;
import com.kingint.web.sys.service.NoticeUserService;
import com.kingint.web.sys.service.UmsAdminService;
import com.kingint.web.util.validateUtil.ValidList;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;



import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;


/**
 * @描述：控制类
 * @作者: wxh
 * @日期: 2020-12-28
 */


//公告
@RestController
@RequestMapping("/serNotice")
@Api(value = "SerNoticeController", description = "后台公告表")
@CrossOrigin
public class SerNoticeController {

    @Autowired
    public NoticeService noticeService;

    @Autowired
    public NoticeUserService noticeUserService;
    @Autowired
    private UmsAdminService umsAdminService;

    @ApiOperation(value = "添加")
    @PostMapping("/create")
    // @PreAuthorize("hasAuthority('notice:create')")
    public Object create(@Validated(Insert.class) @RequestBody(required = false) Notice notice){
        UmsMember currentMember = umsAdminService.getCurrentMember();
        if(currentMember==null){
            return K.error();
        }
        notice.setHotelId(currentMember.getHotelId());//绑定酒店

        notice.setCreateTime(new Date());//设置创建时间
        Integer issue = notice.getIssue();
        notice.setStatus(0);
        notice.setNoticePageview(0);//浏览量初始为0
        if(issue==null||issue.intValue()==0){//说明未发布
        }else{
            Date date = new Date();
            notice.setIssueTime(date).setIssue(1);
        }

        Boolean bool=noticeService.saveOrUpdate(notice);
        if(bool){
            return K.ok().data(notice.getId());
        }else{
            return K.error();
        }
    }

    @ApiOperation(value = "批量添加")
    @PostMapping("/insertList")
    //  @PreAuthorize("hasAuthority('notice:insertList')")
    public Object create(@RequestBody @Validated(Insert.class)  ValidList<Notice> notice){
        Boolean bool=noticeService.saveOrUpdateBatch(notice);
        if(bool){
            return K.ok();
        }else{
            return K.error();
        }
    }
    //=更新只对未发布的做操作
    @ApiOperation(value = "更新")
    @PutMapping("/update")
    //   @PreAuthorize("hasAuthority('notice:update')")
    public Object update(@Validated(Update.class) @RequestBody Notice notice){
        Integer issue = notice.getIssue();
//        notice.setCreateTime(new Date());
        if(issue==null||issue.intValue()==0){//说明未发布
        }else{
            Date date = new Date();
            notice.setIssueTime(date).setIssue(1);
        }
        Boolean bool= noticeService.updateById(notice);
        if(bool){
            return K.ok().data(notice.getId());
        }else{
            return K.error();
        }
    }


    @ApiOperation(value = "删除")
    @DeleteMapping("/delete/{id}")
    //   @PreAuthorize("hasAuthority('notice:delete')")
    public Object delete(@PathVariable("id") Long id){
        QueryWrapper<NoticeUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("notice_id",id);
        List<NoticeUser> list = noticeUserService.list(queryWrapper);
        List<Long> inserts=new ArrayList<>();
        list.forEach(p->{inserts.add(p.getId());});
        if(list.size()>0){
            noticeUserService.removeByIds(inserts);
        }
        Notice notice = new Notice();
        notice.setId(id).setStatus(1);//做逻辑删除
        boolean b = noticeService.updateById(notice);
        if(b){
            return K.ok();
        }else{
            return K.error();
        }
    }

    @ApiOperation(value = "根据名称分页获取列表")
    @GetMapping("/list")
    // @PreAuthorize("hasAuthority('notice:list')")
    public Object getList(
            @RequestParam(value = "issueTime",required = false) String issueTime,
            @RequestParam(value = "issue",required = false) Integer issue,
            @RequestParam(value = "noticeTitle", required = false) String noticeTitle,
            @RequestParam(value = "noticeTop", required = false) Integer noticeTop,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) throws ParseException {
        UmsMember currentMember = umsAdminService.getCurrentMember();
        Integer hotelId = currentMember.getHotelId();
        if(StringUtils.isEmpty(hotelId)){
            return K.error();
        }
        QueryWrapper<Notice> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("hotel_id",hotelId).eq("status",0);
        if(issue!=null){
            queryWrapper.eq("issue",issue);
        }
        if(noticeTitle!=null&&!noticeTitle.equals("")){
            queryWrapper.like("notice_title", noticeTitle);
        }
        if(noticeTop!=null){
            queryWrapper.eq("notice_top",noticeTop);
        }
        if(issueTime!=null&&!issueTime.equals("")){
            SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd yyyy HH:mm:ss z", Locale.US);
            Date parse = sdf.parse(issueTime);
            // String s = parse.toString();
            queryWrapper.ge("issue_time",parse);
        }
        queryWrapper.orderByDesc("create_time");
        Page<Notice> page = new Page<>(pageNum, pageSize);
        IPage<Notice> info=noticeService.page(page,queryWrapper);
        //noticeService.getNoticeList()
        return K.ok().data(info);
    }

    @ApiOperation(value = "根据编号查询信息")
    @GetMapping("/{id}")
    // @PreAuthorize("hasAuthority('notice:get')")
    public Object getItem(@PathVariable("id") Long id){
        Notice notice=noticeService.getById(id);
        return K.ok().data(notice);
    }


    //发布公告
    @GetMapping("/getissue")
    public  Object getissue(@RequestParam("id") Long id,@RequestParam Integer issue){
        Notice byId = noticeService.getById(id);
        if(byId==null){
            return K.error().message("没有找到此公告");
        }
        if(issue.intValue()==0){
            Date date = new Date();
            byId.setIssueTime(date).setIssue(1);
            boolean b = noticeService.updateById(byId);
            return b?K.ok().message("发布成功"):K.error().message("发布失败");
        }
        return K.error().message("发布失败");
    }
}